package com.powernode.filter;

import cn.hutool.json.JSONException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @Author:huxiaochao
 * @Description:全局token过滤器 拦截所有请求
 * @DateTime:2025-03-07 10:44
 **/
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 校验token
     * 1.获取请求路径
     * 2.判断请求路径是否通过
     * 结果
     *  1.通过：不需要验证身份
     *  2.不通过：需要验证身份
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求路径
        String path = request.getPath().toString();
        //3.判断请求路径是否通过
        if(whiteUrlsConfig.getAllowUrls().contains(path)){
            //包含:则请求路径包含在白名单当中,则不需要验证身份
            return chain.filter(exchange);
        }
        //不包含:则请求路径包含在白名单当中,则需要验证身份
        log.info("请求路径:{}",path);
        //从约定好的位置获取Authorization的值
        String token = request.getHeaders().getFirst(AuthConstants.token);
        //判断token是否为空
        if(StringUtils.hasText(token)){
            //从Authorization中获取token
            String tokenValue=token.replaceFirst(AuthConstants.BEARER,"");
            //判断token的值是否有值且是否在redis当中是存在的
            if(StringUtils.hasText(tokenValue) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX+tokenValue)){
                //token值不为空且在redis当中存在,则放行
                return chain.filter(exchange);
            }
        }

        //验证身份没有通过,说明请求不合法,则返回401状态码
        log.error("请求不合法,时间｛｝,请求API路径:{}",new Date(),path);

        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE,HttpConstants.APPLICATION_JSON);

        //设置响应信息
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);

        //创建一个ObjectMapper对象
//        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
